# coding=utf-8
#

import os

from datetime import datetime

from django.core.management.base import BaseCommand

from iminer.agent.models import Agent

from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkecs.v2 import *

from iminer.utils import check_pid

from iminer.tidal.models import TidalAgent

from iminer.sm_log import getLogger


logger = getLogger("iminer.agent.management.commands.cron_check_hw_agent_status")


HW_API_AK = "HMBKL8CG3TWEGQSDYR2G"
HW_API_SK = "53nK542IfRwRUDBLvBvQQbwBacKkPRZXrnoruYcm"


def check_current_server_status(server_info):
    """ 检查当前agent是否需要重启，如果是，则返回server_id """
    now = datetime.now()
    addresses = server_info.addresses

    server_id = ""
    for key, ip_info_list in addresses.items():
        for cur_ip_info in ip_info_list:
            ip = cur_ip_info.addr
            cur_ip_info = cur_ip_info.to_dict()
            ip_type = cur_ip_info["os_ext_ip_stype"]
            if ip_type == "floating":
                server_id = server_info.id
                break

    if not ip:
        print(server_info)
        return None
    # 检查Agent
    agent = Agent.objects.filter(ip=ip, idc="hw").first()

    if not agent:
        return ip
    else:
        return None


class Command(BaseCommand):
    help = "定时遍历agent，发现异常agent"

    def handle(self, *args, **options):
        """ 定时遍历agent，发现异常agent """
        task_name = "pid/daily_get_hw_servers"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            now = datetime.now()

            project_az_list = [{"project_id": "cf300e293b824ea7966711efd01c79dd", "az": "cn-east-3", "cn_name": "华东-上海一"},
                               {"project_id": "dcf3b3b06e5a48af9c2ae988d9488e3e", "az": "cn-south-1", "cn_name": "华南-广州"},
                               {"project_id": "e5b20769b4904199a176d05eefde87c5", "az": "cn-north-4", "cn_name": "华北-北京四"},
                               {"project_id": "ac2364344e244960b564f29013f115d8", "az": "cn-north-9", "cn_name": "华北-乌兰察布一"}]

            for project_az_info in project_az_list:
                project_id = project_az_info["project_id"]
                az = project_az_info["az"]

                print(az, project_id)
                credentials = BasicCredentials(HW_API_AK, HW_API_SK, project_id)
                client = EcsClient.new_builder().with_credentials(credentials).with_region(EcsRegion.value_of(az)).build()

                request = ListServersDetailsRequest()

                request.limit = 1000    # 1次1000条
                response = client.list_servers_details(request)

                for server in response.servers:
                    server_id = server.id

                    ta, _ = TidalAgent.objects.get_or_create(idc="huawei", instance_id=server_id)
                    ta.endpoint = project_id
                    ta.zone = az
                    ta.status = 1
                    ta.save()

